import { useState, useEffect } from "react";
import { getBrowserLang } from "@/utils/util";
import { ConfigProvider, Modal } from "antd";
import { connect } from "react-redux";
import { setLanguage } from "@/redux/modules/global/action";
import { HashRouter } from "react-router-dom";
import AuthRouter from "@/routers/utils/authRouter";
import Router from "@/routers/index";
import useTheme from "@/hooks/useTheme";
import zhCN from "antd/lib/locale/zh_CN";
import enUS from "antd/lib/locale/en_US";
import testCN from "@/config/i18n/cn";
import i18n from "i18next";
import "moment/dist/locale/zh-cn";
import { IPCon } from "./utils/electronIpc";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import { setToken } from "@redux/global/action";

const App = (props: any) => {
	const { language, assemblySize, themeConfig, setLanguage } = props;
	const [i18nLocale, setI18nLocale] = useState(zhCN);
	// 全局使用主题
	useTheme(themeConfig);

	// 设置 antd 语言国际化
	const setAntdLanguage = () => {
		if (language && language == "zh") return setI18nLocale(enUS);
		if (language && language == "en") return setI18nLocale(enUS);
		if (getBrowserLang() == "zh") return setI18nLocale(zhCN);
		if (getBrowserLang() == "en") return setI18nLocale(enUS);
	};

	useEffect(() => {
		setLanguage(language || getBrowserLang());
		i18n.changeLanguage(language || getBrowserLang());
		setAntdLanguage();
	}, [language]);

	useEffect(() => {
		IPCon("reload", () => {
			window.location.reload();
		});

		IPCon("logout", () => {
			Modal.confirm({
				title: "温馨提示 🧡",
				icon: <ExclamationCircleOutlined />,
				content: "是否确认退出登录？",
				okText: "确认",
				cancelText: "取消",
				onOk: () => {
					setToken({});
					const { pathname, origin } = window.location;
					window.location.href = origin + pathname + "#/login";
				},
			});
		});
	}, []);
	return (
		<HashRouter>
			<ConfigProvider locale={i18nLocale} componentSize={assemblySize}>
				<AuthRouter>
					<Router />
				</AuthRouter>
			</ConfigProvider>
		</HashRouter>
	);
};

const mapStateToProps = (state: any) => state.global;
const mapDispatchToProps = { setLanguage, setToken };
export default connect(mapStateToProps, mapDispatchToProps)(App);
